const Warehouse = require('../models/Warehouse');
const { Op } = require('sequelize');

/**
 * 创建仓库
 * BUG: 没有验证容量是否为负数
 */
const createWarehouse = async (req, res) => {
  try {
    const { name, location, capacity, manager, phone, status } = req.body;

    // 验证必填字段
    if (!name || !location || capacity === undefined || !manager) {
      return res.status(400).json({
        success: false,
        message: 'Please provide all required fields (name, location, capacity, manager)'
      });
    }

    // 验证仓库名称是否已存在
    const existingWarehouse = await Warehouse.findOne({ where: { name } });
    if (existingWarehouse) {
      return res.status(400).json({
        success: false,
        message: 'Warehouse name already exists'
      });
    }

    // BUG: 这里故意没有验证 capacity 是否为负数
    // 正确的做法应该是：
    // if (capacity < 0) {
    //   return res.status(400).json({
    //     success: false,
    //     message: 'Capacity cannot be negative'
    //   });
    // }

    // 创建仓库
    const warehouse = await Warehouse.create({
      name,
      location,
      capacity,
      manager,
      phone,
      status: status || 'active'
    });

    res.status(201).json({
      success: true,
      message: 'Warehouse created successfully',
      data: warehouse
    });
  } catch (error) {
    console.error('Error creating warehouse:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to create warehouse',
      error: error.message
    });
  }
};

/**
 * 获取仓库列表
 */
const getWarehouses = async (req, res) => {
  try {
    const { name, status, page = 1, limit = 10 } = req.query;

    // 构建查询条件
    const where = {};
    if (name) {
      where.name = { [Op.like]: `%${name}%` };
    }
    if (status) {
      where.status = status;
    }

    // 分页
    const offset = (page - 1) * limit;

    // 查询
    const { count, rows } = await Warehouse.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    res.json({
      success: true,
      data: {
        warehouses: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('Error fetching warehouses:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch warehouses',
      error: error.message
    });
  }
};

/**
 * 获取单个仓库详情（包含水果数量）
 */
const getWarehouseById = async (req, res) => {
  try {
    const { id } = req.params;
    const Fruit = require('../models/Fruit');

    const warehouse = await Warehouse.findByPk(id, {
      include: [{
        model: Fruit,
        as: 'fruits',
        attributes: ['id', 'name', 'category', 'price', 'stock']
      }]
    });

    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: 'Warehouse not found'
      });
    }

    // 计算水果总数
    const fruitCount = warehouse.fruits ? warehouse.fruits.length : 0;
    
    // 计算总库存数量
    const totalStock = warehouse.fruits 
      ? warehouse.fruits.reduce((sum, fruit) => sum + fruit.stock, 0)
      : 0;

    const result = {
      ...warehouse.toJSON(),
      fruitCount,
      totalStock
    };

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('Error fetching warehouse:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch warehouse',
      error: error.message
    });
  }
};

/**
 * 更新仓库
 * BUG: 没有验证容量是否为负数
 */
const updateWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, location, capacity, manager, phone, status } = req.body;

    const warehouse = await Warehouse.findByPk(id);

    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: 'Warehouse not found'
      });
    }

    // 如果要更新名称，检查名称是否重复
    if (name && name !== warehouse.name) {
      const existingWarehouse = await Warehouse.findOne({ where: { name } });
      if (existingWarehouse) {
        return res.status(400).json({
          success: false,
          message: 'Warehouse name already exists'
        });
      }
    }

    // BUG: 更新时也没有验证 capacity 是否为负数
    // 正确的做法应该是：
    // if (capacity !== undefined && capacity < 0) {
    //   return res.status(400).json({
    //     success: false,
    //     message: 'Capacity cannot be negative'
    //   });
    // }

    // 更新仓库
    await warehouse.update({
      name: name || warehouse.name,
      location: location || warehouse.location,
      capacity: capacity !== undefined ? capacity : warehouse.capacity,
      manager: manager || warehouse.manager,
      phone: phone !== undefined ? phone : warehouse.phone,
      status: status || warehouse.status
    });

    res.json({
      success: true,
      message: 'Warehouse updated successfully',
      data: warehouse
    });
  } catch (error) {
    console.error('Error updating warehouse:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update warehouse',
      error: error.message
    });
  }
};

/**
 * 删除仓库（检查是否有水果关联）
 */
const deleteWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    const FruitWarehouse = require('../models/FruitWarehouse');

    const warehouse = await Warehouse.findByPk(id);

    if (!warehouse) {
      return res.status(404).json({
        success: false,
        message: 'Warehouse not found'
      });
    }

    // 检查是否有水果关联
    const fruitCount = await FruitWarehouse.count({ where: { warehouse_id: id } });
    
    if (fruitCount > 0) {
      return res.status(400).json({
        success: false,
        message: `Cannot delete warehouse. It contains ${fruitCount} fruit(s). Please reassign or delete the fruits first.`
      });
    }

    await warehouse.destroy();

    res.json({
      success: true,
      message: 'Warehouse deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting warehouse:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to delete warehouse',
      error: error.message
    });
  }
};

/**
 * 批量删除仓库
 */
const batchDeleteWarehouses = async (req, res) => {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: 'Please provide warehouse IDs to delete'
      });
    }

    const deletedCount = await Warehouse.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    });

    res.json({
      success: true,
      message: `Successfully deleted ${deletedCount} warehouse(s)`,
      data: { deletedCount }
    });
  } catch (error) {
    console.error('Error batch deleting warehouses:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to batch delete warehouses',
      error: error.message
    });
  }
};

/**
 * 获取仓库中的水果列表
 */
const getWarehouseFruits = async (req, res) => {
  try {
    const { id } = req.params;
    const FruitWarehouse = require('../models/FruitWarehouse');
    const Fruit = require('../models/Fruit');

    const fruits = await FruitWarehouse.findAll({
      where: { warehouse_id: id },
      include: [{
        model: Fruit,
        as: 'fruit',
        attributes: ['id', 'name', 'category', 'price', 'stock']
      }],
      order: [['created_at', 'DESC']]
    });

    res.json({
      success: true,
      data: fruits
    });
  } catch (error) {
    console.error('Error fetching warehouse fruits:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch warehouse fruits',
      error: error.message
    });
  }
};

/**
 * 添加水果到仓库
 */
const addFruitToWarehouse = async (req, res) => {
  try {
    const { id } = req.params;
    const { fruit_id, quantity } = req.body;
    const FruitWarehouse = require('../models/FruitWarehouse');
    const Fruit = require('../models/Fruit');
    const { Op } = require('sequelize');

    // 验证必填字段
    if (!fruit_id || quantity === undefined) {
      return res.status(400).json({
        success: false,
        message: 'Please provide fruit_id and quantity'
      });
    }

    // 验证数量
    if (quantity < 0) {
      return res.status(400).json({
        success: false,
        message: 'Quantity cannot be negative'
      });
    }

    // 检查水果是否存在
    const fruit = await Fruit.findByPk(fruit_id);
    if (!fruit) {
      return res.status(404).json({
        success: false,
        message: 'Fruit not found'
      });
    }

    // 检查是否已存在
    const existing = await FruitWarehouse.findOne({
      where: { fruit_id, warehouse_id: id }
    });

    if (existing) {
      return res.status(400).json({
        success: false,
        message: 'This fruit already exists in this warehouse'
      });
    }

    // 优先检查：请求数量是否超过总库存
    if (quantity > fruit.total_stock) {
      return res.status(400).json({
        success: false,
        message: `Invalid quantity! You are trying to allocate ${quantity} units, but the total stock of "${fruit.name}" is only ${fruit.total_stock} units. Please adjust the quantity.`
      });
    }

    // 计算该水果在所有仓库的总分配量
    const allocatedInWarehouses = await FruitWarehouse.sum('quantity', {
      where: { fruit_id }
    }) || 0;

    // 计算可用库存
    const availableStock = fruit.total_stock - allocatedInWarehouses;

    // 检查可用库存是否充足
    if (quantity > availableStock) {
      return res.status(400).json({
        success: false,
        message: `Insufficient available stock! "${fruit.name}" has ${fruit.total_stock} units in total, ${allocatedInWarehouses} units already allocated to other warehouses, only ${availableStock} units available. You are requesting ${quantity} units.`
      });
    }

    // 创建关联
    const fruitWarehouse = await FruitWarehouse.create({
      fruit_id,
      warehouse_id: id,
      quantity
    });

    // 更新可用库存（总库存 - 所有仓库的分配量）
    const newTotalAllocated = allocatedInWarehouses + quantity;
    await fruit.update({
      stock: fruit.total_stock - newTotalAllocated
    });

    res.status(201).json({
      success: true,
      message: 'Fruit added to warehouse successfully',
      data: fruitWarehouse
    });
  } catch (error) {
    console.error('Error adding fruit to warehouse:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to add fruit to warehouse',
      error: error.message
    });
  }
};

/**
 * 更新仓库中水果的数量
 */
const updateWarehouseFruit = async (req, res) => {
  try {
    const { id, fruitWarehouseId } = req.params;
    const { quantity } = req.body;
    const FruitWarehouse = require('../models/FruitWarehouse');
    const Fruit = require('../models/Fruit');
    const { Op } = require('sequelize');

    if (quantity === undefined) {
      return res.status(400).json({
        success: false,
        message: 'Please provide quantity'
      });
    }

    if (quantity < 0) {
      return res.status(400).json({
        success: false,
        message: 'Quantity cannot be negative'
      });
    }

    const fruitWarehouse = await FruitWarehouse.findOne({
      where: { 
        id: fruitWarehouseId,
        warehouse_id: id 
      }
    });

    if (!fruitWarehouse) {
      return res.status(404).json({
        success: false,
        message: 'Fruit not found in this warehouse'
      });
    }

    // 获取水果信息
    const fruit = await Fruit.findByPk(fruitWarehouse.fruit_id);
    if (!fruit) {
      return res.status(404).json({
        success: false,
        message: 'Fruit not found'
      });
    }

    // 优先检查：请求数量是否超过总库存
    if (quantity > fruit.total_stock) {
      return res.status(400).json({
        success: false,
        message: `Invalid quantity! You are trying to set ${quantity} units, but the total stock of "${fruit.name}" is only ${fruit.total_stock} units. Please adjust the quantity.`
      });
    }

    // 获取当前仓库的原有数量
    const currentQuantity = fruitWarehouse.quantity;
    
    // 计算可以使用的最大数量：当前可用库存 + 当前仓库原有数量
    const maxAvailableForThisWarehouse = fruit.stock + currentQuantity;

    // 检查是否超过可用数量
    if (quantity > maxAvailableForThisWarehouse) {
      return res.status(400).json({
        success: false,
        message: `Insufficient available stock! "${fruit.name}" currently has ${fruit.stock} units available, plus ${currentQuantity} units in this warehouse. You can set up to ${maxAvailableForThisWarehouse} units, but you are requesting ${quantity} units.`
      });
    }
    
    // 计算该水果在其他仓库的总分配量（用于更新可用库存）
    const allocatedInOtherWarehouses = await FruitWarehouse.sum('quantity', {
      where: { 
        fruit_id: fruitWarehouse.fruit_id,
        id: { [Op.ne]: fruitWarehouseId }
      }
    }) || 0;

    // 更新仓库中的数量
    await fruitWarehouse.update({ quantity });

    // 计算更新后的总分配量
    const totalAllocated = allocatedInOtherWarehouses + quantity;

    // 更新可用库存
    await fruit.update({
      stock: fruit.total_stock - totalAllocated
    });

    res.json({
      success: true,
      message: 'Quantity updated successfully',
      data: fruitWarehouse
    });
  } catch (error) {
    console.error('Error updating warehouse fruit:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update fruit quantity',
      error: error.message
    });
  }
};

/**
 * 从仓库移除水果
 */
const removeFruitFromWarehouse = async (req, res) => {
  try {
    const { id, fruitWarehouseId } = req.params;
    const FruitWarehouse = require('../models/FruitWarehouse');
    const Fruit = require('../models/Fruit');
    const { Op } = require('sequelize');

    const fruitWarehouse = await FruitWarehouse.findOne({
      where: { 
        id: fruitWarehouseId,
        warehouse_id: id 
      }
    });

    if (!fruitWarehouse) {
      return res.status(404).json({
        success: false,
        message: 'Fruit not found in this warehouse'
      });
    }

    // 获取水果信息
    const fruit = await Fruit.findByPk(fruitWarehouse.fruit_id);
    if (fruit) {
      // 计算该水果在其他仓库的总分配量
      const allocatedInOtherWarehouses = await FruitWarehouse.sum('quantity', {
        where: { 
          fruit_id: fruitWarehouse.fruit_id,
          id: { [Op.ne]: fruitWarehouseId }
        }
      }) || 0;

      // 更新可用库存
      await fruit.update({
        stock: fruit.total_stock - allocatedInOtherWarehouses
      });
    }

    // 删除关联
    await fruitWarehouse.destroy();

    res.json({
      success: true,
      message: 'Fruit removed from warehouse successfully'
    });
  } catch (error) {
    console.error('Error removing fruit from warehouse:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to remove fruit from warehouse',
      error: error.message
    });
  }
};

module.exports = {
  createWarehouse,
  getWarehouses,
  getWarehouseById,
  updateWarehouse,
  deleteWarehouse,
  batchDeleteWarehouses,
  getWarehouseFruits,
  addFruitToWarehouse,
  updateWarehouseFruit,
  removeFruitFromWarehouse
};

